package _3sort.src;

import java.util.Arrays;

public class _9shellSort {
    public static void shellSort(int[] arr) {
        int n = arr.length;

        // 初始间隔 gap = n/2，逐步缩小至 1
        for (int gap = n / 2; gap > 0; gap /= 2) {
            // 从 i=gap 开始，避免无效循环
            for (int i = gap; i < n; i++) {
                int temp = arr[i];
                int j;
                for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
                    arr[j] = arr[j - gap];
                }
                arr[j] = temp;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {8, 3, 5, 1, 4, 7, 2, 6};
        shellSort(arr);
        System.out.println(Arrays.toString(arr)); // [1, 2, 3, 4, 5, 6, 7, 8]
    }
}